package cn.css0209.applicationdemo190509.book.DB.Dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;

import cn.css0209.applicationdemo190509.book.BookDo;
import cn.css0209.applicationdemo190509.book.DB.MyDBHelper;

public class BookDAO {
    private Context context;
    private static BookDAO instance;
    private MyDBHelper helper;

    public BookDAO(Context context) {
        this.context = context;
        helper = new MyDBHelper(context);
    }

    public static BookDAO newInstance(Context context) {
        if (instance == null) {
            instance = new BookDAO(context);
        }
        return instance;
    }

    public String insert(String name, String phone) {
        long result = -1;
        SQLiteDatabase db = helper.getWritableDatabase();
        if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(phone)) {
            ContentValues value = new ContentValues();
            value.put("name", name);
            value.put("phone", phone);
            result = db.insert("student", null, value);
        }
        db.close();
        if (result >= 0) {
            return "添加成功";
        } else {
            return "添加失败";
        }
    }

    public String delete(String name) {
        SQLiteDatabase db = helper.getWritableDatabase();
        if (!TextUtils.isEmpty(name)) {
            String sql = "delete from student where name = ?";
            db.execSQL(sql, new String[]{name});
            db.close();
            return "删除成功";
        } else {
            db.close();
            return "删除失败";
        }
    }

    public String update(String name, String phone) {
        SQLiteDatabase db = helper.getWritableDatabase();
        if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(phone)) {
            String sql = "update student set phone = ? where name = ?";
            db.execSQL(sql, new String[]{phone, name});
            db.close();
            return "修改成功";
        } else {
            db.close();
            return "修改失败";
        }
    }

    public List<BookDo> select() {
        List<BookDo> bookDos = new ArrayList<>();
        SQLiteDatabase db = helper.getReadableDatabase();
        String sql = "select * from student";
        Cursor cursor = db.rawQuery(sql, null);
        if (cursor != null && cursor.getCount() > 0) {
            BookDo bookDo;
            while (cursor.moveToNext()) {
                bookDo = new BookDo();
                int id = cursor.getInt(0);
                String name = cursor.getString(1);
                String phone = cursor.getString(2);
                bookDo.setId(id);
                bookDo.setName(name);
                bookDo.setPhone(phone);
                bookDos.add(bookDo);
            }
        }
        cursor.close();
        db.close();
        return bookDos;
    }
}
